package com.rising.face.suanfa.threadprint;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author: rising
 * @Description:
 * @Date: create in 2021/1/10 14:38
 */
public class ThreadPrint {

    private String cThredName = "AA"; //当前执行线程，默认是AA

    Lock lock = new ReentrantLock();
    Condition conditionA = lock.newCondition();
    Condition conditionB = lock.newCondition();
    Condition conditionC = lock.newCondition();

    public void publicPrint5() {
        lock.lock();
        try {
            while (!"AA".equals(cThredName)) {
                conditionA.await();
            }
            System.out.print("启动"+Thread.currentThread().getName()+"线程：");
            for (int i=0; i < 5; i++) {
                Thread.sleep(100);
                System.out.print(Thread.currentThread().getName() + "\t");
            }
            System.out.println();
            cThredName = "BB";
            conditionB.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void publicPrint10() {
        lock.lock();
        try {
            while (!"BB".equals(cThredName)) {
                conditionB.await();
            }
            System.out.print("启动"+Thread.currentThread().getName()+"线程：");
            for (int i=0; i < 10; i++) {
                Thread.sleep(100);
                System.out.print(Thread.currentThread().getName() + "\t");
            }
            System.out.println();
            cThredName = "CC";
            conditionC.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void publicPrint15() {
        lock.lock();
        try {
            while (!"CC".equals(cThredName)) {
                conditionC.await();
            }
            System.out.print("启动"+Thread.currentThread().getName()+"线程：");
            for (int i=0; i < 15; i++) {
                Thread.sleep(100);
                System.out.print(Thread.currentThread().getName() + "\t");
            }
            System.out.println();
            System.out.println("----------------------等待两秒继续下一组----------------------");
            Thread.sleep(2 * 1000);
            cThredName = "AA";
            conditionA.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

}
